<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="yes" name="apple-touch-fullscreen">
    <meta content="telephone=no,email=no" name="format-detection">
    <!--防止css、js资源缓存-->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <script type="text/javascript" src="asserts/resource/js/flexible_C.js" ></script>
	<title>电子围栏</title>
	<link rel="stylesheet" href="asserts/resource/css/common.css">
	<link rel="stylesheet" href="asserts/resource/css/css.css">
	<style type="text/css">
		body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
	</style>
	<script type="text/javascript" src="asserts/resource/js/jquery.min.js"></script>
    <script type="text/javascript" src="asserts/resource/layer/mobile/layer.js"></script>
	<script type="text/javascript" src="asserts/resource/js/js.js"></script>
	<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=A4LmXLHVeMzGbVYqMvC4i5tiodzwqKn5"></script>
</head>
<body>
    <div id="allmap"></div>
    <div class="circle_add_sub_wrap">
        <div class="circle_add_sub">
            <span class="substract" id='substract'>-</span>
            <div class="dl">
                <dl>
                    <dd>
                        <div class="progressbar" id="progressbar" data-value="0" data-radius="100"></div>
                        <p class="mile"><a id="miles"></a>米</p>
                    </dd>
                </dl>
            </div>
            <span class="addition" id="addition">+</span>
        </div>

    </div>
    <div class="positionIcon">
        <div id="old" onclick="getData()"></div>
        <div id="phone"></div>
    </div>
<div id="aroundWrap">
	<div class="around_In" id="around">
		<a><i class="AroundIcon"></i></a><input class="NameInput" type="text" value="" placeholder=""/><a class="saveName">保存</a>
	</div>
</div>
<div class="crosswrap">
    <img src="asserts/resource/img/cross.png" alt="cross">
    <canvas id="canvas" class="blueCircle"></canvas>
</div>
</body>
</html>
<script type="text/javascript" src="asserts/resource/js/js.js"></script>
<script type="text/javascript">
    var datas = JSON.parse(localStorage.AreaObj);
    var circlePoint;
    var areaName ;
    var dataId;
    var radius;
    if(datas) {
        areaName = datas.areaName;
        dataId = datas.dataId;
        radius = datas.radui;
        $(".NameInput").attr("placeholder", areaName);
        $(".NameInput").attr("value", areaName);
        //圆位置
        circlePoint=new BMap.Point(datas.lngR,datas.latR);
    }else {
        radius=100;//初始半径
    }



    var map = new BMap.Map("allmap");

    //老人位置
    var menPoint;

    //老人marker
    var menMarker;

    //手机位置
    var phonePoint;

    //手机marker
    var phoneMarker; //创建marker对象

    var len;//半径加减条长度

    var oldIcon = new BMap.Icon("asserts/resource/img/imei.png", new BMap.Size(15,30));

    var phoneIcon = new BMap.Icon("asserts/resource/img/self.png", new BMap.Size(15,30));

    //获取老人位置
    getData();

    //---手机定位
    var geolocation = new BMap.Geolocation();

    geolocation.getCurrentPosition(function(r){
        phonePoint = new BMap.Point(r.point.lng,r.point.lat);

        if(this.getStatus() == BMAP_STATUS_SUCCESS){
            if(datas) {
                setCenter(circlePoint, radius);
            }else {
                setCenter(phonePoint,radius);
            }
            whichsize(radius);
        }
        else {
            layerMsg('failed'+this.getStatus(),2);
        }
    },{enableHighAccuracy: true});

    function getData(){
        $.ajax({
            //几个参数需要注意一下
            type: "POST",//方法类型
            async: false, // 使用同步方式
            dataType: "json",//预期服务器返回的数据类型
            url: projectName + "/position/realtime" ,//url
            //data: {"imei":username,"password":password},
            success: function (result) {
                if (result.status == 1) {
                    //查询成功，终端信息，在result中取。
                    var data=result.data;
                    menPoint=new BMap.Point( data.longitudeShow,data.latitudeShow);
                    menMarker=new BMap.Marker(menPoint,{icon:oldIcon});
                }else{
                    layerMsg(result.msg,2);
                }
            },
            error : function() {
                layerMsg("网络异常!",2);
            }
        });
    }
    //画圆
    function drawCircle(radius,zoom){
        //15==1800  16===1000 17===550 18===290 14===2800  13===6500 12===12000 11===20000
        var cWidthHeight;
        switch(zoom)
        {
            case 18:
                cWidthHeight = (radius/290)*zoom;
                break;
            case 17:
                cWidthHeight = (radius/550)*zoom;
                break;
            case 16:
                cWidthHeight = (radius/1000)*zoom;
                break;
            case 15:
                cWidthHeight = (radius/1800)*zoom;
                break;
            case 14:
                cWidthHeight = (radius/2800)*zoom;
                break;
            case 13:
                cWidthHeight = (radius/6500)*zoom;
                break;
            case 12:
                cWidthHeight = (radius/12000)*zoom;
                break;
            case 11:
                cWidthHeight = (radius/20000)*zoom;
                break;
            default:
                cWidthHeight = 0;
        }

        $("#canvas").css(
            {"width":cWidthHeight + "rem",
                "height":cWidthHeight + "rem",
                "top":"calc(50% - "+cWidthHeight/2+"rem)",
                "left":"calc(50% - "+cWidthHeight/2+"rem)"
            }
        )
    }

    //设置中心
    function setCenter(point,radius) {

        phoneMarker = new BMap.Marker(phonePoint,{icon:phoneIcon});

        map.centerAndZoom(point, 15);

        map.setMinZoom(3);

        map.setMaxZoom(18);

        map.addOverlay(phoneMarker);

        drawCircle(radius,15);
        //获取老人位置
        getData();

        map.addOverlay(menMarker); //在地图中添加老人marker
    }

    //居中当前定位
    var phone = document.getElementById("phone");
    var old = document.getElementById("old");

    old.addEventListener("click",function(){
        map.centerAndZoom(menPoint,15);
    });

    phone.addEventListener("click",function(){
        map.centerAndZoom(phonePoint,15)
    });

    //加减半径
    $("#addition").on("click",function(){
        if (!radius) {

            radius = parseInt($(this).siblings(".dl").find('#progressbar').attr("data-radius"));


        }else {

            radius = parseInt(radius);

        }

        radius += 100;

        if (radius > 5000){
            radius=5000;
        }

        whichsize(radius);

        drawCircle(radius,map.getZoom());

    })

    $("#substract").on("click",function(){

        if (!radius) {

            radius = parseInt($(this).siblings(".dl").find('#progressbar').attr("data-radius"));

        }else {

            radius = parseInt(radius);

        }

        radius -= 100;

        if (radius < 100){
            radius=100;
        }

        whichsize(radius);

        drawCircle(radius,map.getZoom());
    })

    //半径显示、进度条换算
    function whichsize(radius){

        $('#progressbar').attr("data-radius",radius);

        len = radius * 0.00086;

        $("#progressbar").css("width",len + 'rem' );

        $("#miles").text(radius);
    }

    //地图更改缩放级别结束时触发触发此事件
    map.addEventListener("zoomend",function () {
        drawCircle(radius,map.getZoom());
    })


    //编辑时
    var railName,lngPoint,latpoint,Cradiu,centerPoint;
    $(".saveName").on("touchstart",function(){

        centerPoint = map.getCenter();

        railName = $(".NameInput").val();

        railName = railName.trim();

        Cradiu = $('#miles').text();

        lngPoint = centerPoint.lng;

        latpoint = centerPoint.lat;

        var url;
        var data;

        if(datas){
            url= "/eleFence/updateFence";
            data={
                elefenceId: dataId,
                elefenceName: railName,
                centerLongitude: parseInt(lngPoint * 1000000),
                centerLatitude: parseInt(latpoint * 1000000),
                radius: parseInt(Cradiu)
            };
        }else {
            url= "/eleFence/addFence";
            data={
                elefenceName:railName,
                centerLongitude:parseInt(lngPoint*1000000),
                centerLatitude:parseInt(latpoint*1000000),
                radius:parseInt(Cradiu)
            };
        }

        //添加或编辑
        $.ajax({
            type: "POST",
            contentType: "application/json;charset=UTF-8",
            url: url,
            async: true,
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (data) {
                if (data.status == 1) {
                    window.location.href = 'AreaEdit.html';
                }
                if(data.status == 0){
                    layerMsg(data.msg,2);
                }

            },
            error: function () {
                layerMsg("网络异常!",2);

            }
        });

    })

    //---------添加地图类型控件-----------
    map.addControl(new BMap.MapTypeControl({
        mapTypes:[
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ],
        offset : new BMap.Size(10,50)
    }));

    // ---------定义缩放控件  -----------
    function ZoomControl() {
        // 设置默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT;
        this.defaultOffset = new BMap.Size(10, 100);
    }
    // 通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMap.Control();

    // 自定义控件必须实现initialize方法，并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    ZoomControl.prototype.initialize = function (map) {
        //+-包裹层
        var mapwrap = document.createElement("div");
        mapwrap.className = 'zoomwrap';
        //创建一个放大img
        var plus_div = document.createElement("div");
        plus_div.className = 'plusDiv';
        var map_p_lus = document.createElement("p");
        map_p_lus.className = 'plus';
        var map_plus = document.createElement("img");
        map_plus.setAttribute("src", "asserts/resource/img/plus.png");

        //为img设置点击事件
        map_plus.onclick = function () {
            map.zoomTo(map.getZoom() + 2);
        }
        //创建一个缩小img
        var minus_div = document.createElement("div");
        minus_div.className = 'minusDiv';
        var map_m_inus = document.createElement("p");
        map_m_inus.className = 'minus';
        var img_minus = document.createElement("img");
        img_minus.setAttribute("src", "asserts/resource/img/minus.png");
        img_minus.onclick = function () {
            map.zoomTo(map.getZoom() - 2);
        }
        //添加放大的img图标到div中
        mapwrap.appendChild(plus_div);
        plus_div.appendChild(map_p_lus);
        map_p_lus.appendChild(map_plus);
        //添加缩小的img图标到div中
        mapwrap.appendChild(minus_div);
        minus_div.appendChild(map_m_inus);
        map_m_inus.appendChild(img_minus);
        //添加DOM元素到地图中
        map.getContainer().appendChild(mapwrap);
        //将DOM元素返回；
        return mapwrap;
    }

    // 创建控件实例
    var myZoomCtrl = new ZoomControl();
    // 添加到地图当中
    map.addControl(myZoomCtrl);

</script>